// 添加奖惩界面
import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import ReactScrollbar from 'react-scrollbar-js';
require("./home.css");

class AddRP extends React.Component{
    constructor(){
        super();
        this.state = {
            query : [],
            addRPText: '',
            addQueryData: []
        }
    }

    componentWillMount(){
        this.FetchData();
    }

    //将当前选中的员工的user_id，company_id提交到服务器然后setState到query里面
    FetchData(){
        const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
        fetch("http://121.196.202.247:1010/select_user/?format=json", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json; charset=utf-8"
            },
            body: JSON.stringify({
                user_id: this.props.location.query.selectUser,
                company_id: userSessionStorage.company_id,
            })
        }) .then((response) => response.json())
            .then((responseText) => {
                this.setState({query:responseText});
                console.log("11111"+JSON.stringify(responseText));
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    handleSubmit(e) {
        e.preventDefault();
        if(ReactDOM.findDOMNode(this.refs.addRP).value.trim() == ''){
            alert("请输入要添加的输入奖惩信息！");
        }else{
            const userSessionStorage = JSON.parse(window.sessionStorage.getItem('userStorage'));
            fetch("http://121.196.202.247:1010/prize_punish/?format=json", {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    "Content-Type": "application/json; charset=utf-8"
                },
                body: JSON.stringify({
                    rwdpun_user: this.state.query[0].user_id,
                    rewpun_people_id: userSessionStorage.user_id,
                    is_black: 0,
                    rwdpun_content: this.state.addRPText
                })
            }) .then((response) => response.json())
                .then((responseText) => {
                    console.log("33333"+responseText);
                    console.log("33333"+JSON.stringify(responseText));
                    this.setState({addQueryData:responseText});
                    alert("添加奖惩操作成功！");
                }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
        }
    }

    // 实时根据输入的值改变奖惩信息内的值
    handleChange(e){
        this.setState({addRPText: e.target.value});
    }

    render(){
        const style = {
            scroll:{
                width: "100%",
                height: "250px",
                border: "1px solid #bbb",
                marginTop: "30px"
            }
        };
        console.log(this.props.location.query.selectUser);
        console.log(this.state.query);
        console.log(this.state.query.length);
        if(this.state.query.length == 1){
            return(
                <form className="add_RP" onSubmit={function (e) {this.handleSubmit(e)}.bind(this)}>
                    <p>当前选定的员工姓名为：{this.state.query[0].user_name} ，职信号为：{this.props.location.query.selectUser}，手机号为：{this.state.query[0].user_phone}。</p>
                    <p>如需添加奖惩请填写相应原因，例如“表现卓越，年度劳动奖；打架降级等等”。</p>
                    <textarea placeholder="请输入要添加的奖惩信息......" value={this.state.addRPText} onChange={this.handleChange.bind(this)} ref="addRP"/><br/>
                    <input type="submit" value="确认添加" className="add_RP_submit"/>
                    <Link to='/home_query_hr'><input type="button" value="返回" className="add_RP_back"/></Link>
                    <div>
                        <ReactScrollbar style={style.scroll}>
                            <div>
                                <RPData selectID={this.props.location.query.selectUser} addQuery={this.state.addQueryData}/>
                            </div>
                        </ReactScrollbar>
                    </div>
                </form>
            );
        }else{
            return(
                    <p>正在加载中......</p>
            );
        }
    }
}

class RPData extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            query: [],
            selectUser: "72"
        }
    }

    componentWillMount(){
        this.LoadData();
    }

    // 初加载奖惩历史
    LoadData(){
        fetch("http://121.196.202.247:1010/prize_punish/?user_id="+this.state.selectUser+"&li_zhi=1", {
            method: "GET",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json; charset=utf-8"
            },
        }) .then((response) => response.json())
            .then((responseText) => {
                console.log("22222"+responseText);
                console.log("22222"+JSON.stringify(responseText));
                this.setState({query:responseText});
            }).catch((error) => {alert(error+"连接职信服务器失败，请查看网络连接状态并刷新页面！")});
    }

    render(){
        // 初加载奖惩历史界面
        let body = [];
        if (this.state.query.length == 0){
            body.push(<p>该用户没有奖惩记录</p>);
        }else{
            for(let i=0;i<this.state.query.length;i++) {
                body.push(
                    <div>
                        <hr/>
                        <div>
                            <p>时间：{this.state.query[i].rwdpun_date}&nbsp;&nbsp;内容：{this.state.query[i].rwdpun_content}
                            &nbsp;&nbsp;给予者（HR）：{this.state.query[i].rewpun_people_id}</p>
                        </div>
                        <hr/>
                    </div>
                );
            }
        }

        // 父组件的addQueryData[]数组
        var addQueryData = this.props.addQuery;
        if(addQueryData.length > 0) {
            body.length = 0;
            body.push(<p>奖惩历史：</p>);
            for(let i=0;i<addQueryData.length;i++) {
                body.push(
                    <div>
                        <hr/>
                        <div>
                            <p>时间：{addQueryData[i].rwdpun_date}&nbsp;&nbsp;内容：{addQueryData[i].rwdpun_content}
                                &nbsp;&nbsp;给予者（HR）：{addQueryData[i].rewpun_people_id}</p>
                        </div>
                        <hr/>
                    </div>
                );
            }
        }

        return(
            <div>
                {body}
            </div>
        );
    }
}

export default AddRP;